package com.gimhon.login.interceptor;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.gimhon.login.constant.ResultCode;
import com.gimhon.login.entity.Response;
import com.gimhon.login.entity.User;
import lombok.extern.log4j.Log4j2;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * 用户权限拦截器
 */
@Log4j2
@Component
public class AuthInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        HttpSession session = request.getSession();
        User user = (User) session.getAttribute("user");
        if (user == null) {
            log.info("该用户未登录，或登陆已过期，没有权限访问服务");
            String servletPath = request.getServletPath();
            // 如果是静态页请求则重定向到登陆页
            if (servletPath.contains(".html")) {
                String contextPath = request.getContextPath();
                response.sendRedirect(contextPath + "/page/login.html");
            }
            returnErrorMessage(response, "");
            return false;
        }
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }

    /**
     * 构造返回的错误信息
     *
     * @param response
     * @param message
     */
    private void returnErrorMessage(HttpServletResponse response, String message) throws IOException {
        response.setContentType("application/json");
        response.setCharacterEncoding("UTF-8");
        PrintWriter out = response.getWriter();
        ObjectMapper mapper = new ObjectMapper();
        out.print(mapper.writeValueAsString(Response.error(ResultCode.NOT_LOGIN)));
        out.flush();
    }
}
